﻿using Models;
using SIE.SCADA.Common.Log;
using SIE.SCADA.Helper;
using SIE.SCADA.SqlSugar;
using SIE.SCADA.ZemtDemo;
using SIE.SCADA.ZemtDemo.MqClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;

namespace SCADA_DAQ.ZEMT.Server
{
    /// <summary>
    /// 工单信息请求与接收
    /// </summary>
    public class WoInfoManager : MqMangerBase<WoInfoManager>
    {
        private readonly string IfaceName = "GET_MESPLANINFO"; //接口名称
        private readonly string EXCHANAGE = "ZEMT_MQ_EXCHANGE_GET_MESPLANINFO";
        private readonly string ROUTEKEY = "GET_MESPLANINFO_SIE";
        private AdvancedThread _thread;

        public string line_names = Env.LineName.Value;
        public string LineGroupName = Env.LineGroupName.Value;

        private void Loop()
        {
            var datetime = DateTime.Now.AddDays(0).ToString("yyyyMMdd");
            string[] linenames= line_names.Split(',');
            foreach (var item in linenames) {
                Send(datetime, item);
                Logger.Info($"WOInfoRequest{datetime}"+",产线："+ item);
            }
            
            
        }

        //请求获取派工单
        public void Send(string WorkDate,string line)
        {
            try
            {
                var plant = new PlanaskItem()
                {
                    workdate = WorkDate,
                    workbin = line
                };
                var plant_list = new List<PlanaskItem>();
                plant_list.Add(plant);
                var wos = new WO()
                {
                    planask = plant_list
                };
                var res = mqhelper.TopicExchangePublish(wos, EXCHANAGE, "", $"{IfaceName}.{LineGroupName}", true, false, true, false);
                if (res.Success)
                    System.Diagnostics.Debug.WriteLine("数据已推送完成的！");
                else
                    System.Diagnostics.Debug.WriteLine("数据推送失败！\n" + res.Message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message); 
            }
        }

        public override void Start()
        {            
            DataReceive();
            //Loop();
            var interval = (Env.AutoGet.Value.ObjToInt());
            interval = (interval == 0 ? 3 : interval) * 1000 * 60 * 60;
            _thread = new AdvancedThread(Loop, interval);
            _thread = new AdvancedThread(Loop, 3 * 60 * 60 * 1000);
            _thread.Start();
        }

        /// <summary>
        /// KJF 20210329 新增
        /// 手动发送请求工单信息
        /// </summary>
        public void Request(string datetime,string linename)
        {
            Send(datetime, linename);
            Logger.Info($"WOInfoRequest{datetime}");
        }


        void DataReceive()
        {

                //派工单接口
                var res1 = mqhelper.TopicExchangeConsumer<WoRoot>((data) =>
                {
                    SaveWO(data);
                    return true;
                }, EXCHANAGE, $"ZEMT_MQ_SIE_{IfaceName}", $"{ROUTEKEY}.{LineGroupName}", true, false, true, false);

        }

        #region Downlod 派工单


        //解析Json文件
        private void SaveWO(WoRoot dataMessage)
        {
            Logger.Info("从MES收到派工单消息！");

            List<smdc_disid_t> itemModels = new List<smdc_disid_t>();

            var rts = dataMessage;
            
            if (rts.qusdatas != null)
            {
                foreach (var rt in rts.qusdatas)
                {
                    if (rt.sndatas != null)
                    {
                        using (var ctx = pgsql.GetClient())
                        {
                            try
                            {
                                if (pgsql.DBClient is SmdcOrmClient ormClient)
                                {
                                    foreach (var item in rt.sndatas)
                                    {
                                        var materials = ormClient.SqlSugarClient.Queryable<smdc_disid_t>().Where(m => m.disidno == rt.disid && m.serial_number == item.snno).First();
                                        if (materials != null)
                                        {

                                        }
                                        else
                                        {
                                            smdc_disid_t data = new smdc_disid_t()
                                            {

                                                disidno = rt.disid,
                                                mbom = rt.edt_code,
                                                poid = rt.poid,
                                                workbin = rt.workbin,
                                                workbinname = rt.workbinname,
                                                matid = rt.matid.Trim(),
                                                matid_old = rt.matid_old,
                                                matdesc = rt.matdesc,
                                                quantity = rt.quantity,
                                                workseq = rt.disseq?.Trim(),
                                                workseqdesc = rt.disseqdesc,
                                                disque = rt.op_group?.Trim(),
                                                disque_desc = rt.op_groupdesc,
                                                sdno = rt.sdno,
                                                cusname = rt.cusname,
                                                cusmsg = rt.cusmsg,
                                                planerid = rt.planerid,
                                                planername = rt.planername,
                                                begintime = DateTime.ParseExact(rt.begintime, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture),
                                                endtime = rt.endtime.ObjToDate(),
                                                createtime_dt = DateTime.Now,
                                                serial_number = item.snno
                                            };
                                            itemModels.Add(data);
                                        }
                                    }
                                }
                            }
                            catch(Exception  ex)
                            {
                                Logger.Warn(ex.Message);
                                Logger.Warn(ex.StackTrace);
                            }
                        }
                    }
                }
                // itemModels = GetItemModelData(itemModels);
                InsertItemModel(itemModels);
            }
        }

        //把解析的数据存入DB
        private void InsertItemModel(List<smdc_disid_t> models)
        {
            using (var ctx = pgsql.GetClient())
            {
                try
                {
                    if (pgsql.DBClient is SmdcOrmClient ormClient)
                    {
                        ormClient.SqlSugarClient.Insertable<smdc_disid_t>(models).IgnoreColumns(it=>it == "id")
                            .IgnoreColumns(ignoreNullColumn:true).ExecuteCommand();
                        Logger.Info("插入物料数量：" + models.Count);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Warn(ex.Message);
                }
            }
        }
        #endregion

    }

    public class PlanaskItem
    {
        /// <summary>
        /// 请求派工单时间
        /// </summary>
        public string workdate { get; set; }
        /// <summary>
        /// 请求派工线别
        /// </summary>
        public string workbin { get; set; }
    }

    public class WO
    {
        /// <summary>
        /// 请求派工单
        /// </summary>
        public List<PlanaskItem> planask { get; set; }
    }


}
